package com.example.myweather.Activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewOutlineProvider
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.myweather.Adapter.ForecastAdapter
import com.example.myweather.R
import com.example.myweather.ViewModel.WeatherViewModel
import com.example.myweather.databinding.ActivityMainBinding
import com.example.myweather.model.CurrentResponseApi
import com.example.myweather.model.ForecastResponseApi
import com.example.myweather.ui.theme.MyWeatherTheme
import com.github.matteobattilana.weather.PrecipType
import eightbitlab.com.blurview.RenderScriptBlur
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.Calendar

class MainActivity : ComponentActivity() {
    lateinit var binding: ActivityMainBinding
    private val weatherViewModel:WeatherViewModel by viewModels()
//    使用by lazy语法可以实现懒加载，延迟初始化变量。 懒加载可以节省资源和提高性能，只有在需要使用变量时才会进行实例化。
    private val calendar by lazy { Calendar.getInstance() }
    private val forecastAdapter by lazy{ForecastAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

//        window.apply {
       // // 添加窗口标志，表示窗口会绘制系统栏的背景
//            addFlags(windowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
//            statusBarColor= Color.TRANSPARENT
//        }

        window.apply {
            // 添加窗口标志，表示窗口会绘制系统栏的背景
            addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)

        }
        binding.apply {
            var lat = intent.getDoubleExtra("lat", 51.50).takeIf { it != 0.0 } ?: 51.50
            var lon= intent.getDoubleExtra("lon", -0.12).takeIf { it != 0.0 } ?: -0.12
            var name= intent.getStringExtra("name") ?: "London"

//            if(lat==0.0){
//                lat=51.50
//                lon=-0.12
//                name="London"
//            }

//            addCity.setOnClickListener{
//                startActivity(Intent(this@MainActivity,CityListActivity::class.java))
//            }

            // 设置点击事件监听器
            addCity.setOnClickListener {
                try {
                    startActivity(Intent(this@MainActivity, CityListActivity::class.java))
                } catch (e: Exception) {
                    // 捕获并打印异常
                    e.printStackTrace()
                }
            }


//            currentWeather temp
            // 显示城市名字
            cityNameTxt.text=name
            // 显示进度条
            progressBar.visibility=View.VISIBLE
            // 加载当前天气数据
            weatherViewModel.loadCurrentWeather(lat,lon,"metric").enqueue(object :
                retrofit2.Callback<CurrentResponseApi>{
                override fun onResponse(
                    call: Call<CurrentResponseApi>,
                    response: Response<CurrentResponseApi>
                ) {
                   if (response.isSuccessful){
                       val data=response.body()
                       // 隐藏进度条
                       progressBar.visibility=View.GONE
                       // 显示详细布局
                       detailLayout.visibility=View.VISIBLE
                       // 更新天气UI
                       data?.let {

                           statusTxt.text=it.weather?.get(0)?.main?:"-"
                           windTxt.text=it.wind?.speed?.let { Math.round(it).toString() }+"Km"
                           humidityTxt.text=it.main?.humidity?.toString()+"%"
                           CurrentTempTxt.text=it.main?.temp?.let { Math.round(it).toString() }+"°"
                           maxTempTxt.text=it.main?.tempMax?.let { Math.round(it).toString() }+"°"
                           minTempTxt.text=it.main?.tempMin?.let { Math.round(it).toString() }+"°"

                           val drawable=if (isNightNow()) R.drawable.night_bg
                           else{
//                               it.weather?.get(0)?.icon.let { it1->setDynamicallyWallpaper(it1) }
                               setDynamicallyWallpaper(it.weather?.get(0)?.icon?:"-")

                           }
                           bgImage.setImageResource(drawable)
                           setEffectRainSnow(it.weather?.get(0)?.icon?:"-")
                       }
                   }
                }
                //错误处理
                override fun onFailure(call: Call<CurrentResponseApi>, t: Throwable) {
                   Toast.makeText(this@MainActivity,t.toString(),Toast.LENGTH_SHORT).show()
                }

            })

//             setting blue view // 设置模糊视图
            var radius=10f
            val decorView=window.decorView
            val rootView=(decorView.findViewById(android.R.id.content)as ViewGroup?)
            val windowBackground=decorView.background

            rootView?.let {
                blueView.setupWith(it,RenderScriptBlur(this@MainActivity))
                    .setFrameClearDrawable(windowBackground)
                    .setBlurRadius(radius)
                blueView.outlineProvider= ViewOutlineProvider.BACKGROUND
                blueView.clipToOutline=true

            }

//            forecastWeather temp// 加载未来天气预报数据
            weatherViewModel.loadForecastWeather(lat,lon,"metric")
                .enqueue(object :retrofit2.Callback<ForecastResponseApi>{
                override fun onResponse(
                    call: Call<ForecastResponseApi>,
                    response: Response<ForecastResponseApi>
                ) {
                    if(response.isSuccessful){
                        val data=response.body()
                        blueView.visibility=View.VISIBLE
                        // 更新适配器数据// 更新未来天气预报适配器数据
                        data?.let {
                            forecastAdapter.differ.submitList(it.list)
                            forecastView.apply {
                                layoutManager=LinearLayoutManager(this@MainActivity,
                                    LinearLayoutManager.HORIZONTAL,false)
                                adapter=forecastAdapter
                            }
                        }
                    }
                }

                override fun onFailure(call: Call<ForecastResponseApi>, t: Throwable) {
                    TODO("Not yet implemented")
                }

            })
        }
    }



    private fun isNightNow():Boolean{
       return calendar.get(Calendar.HOUR_OF_DAY)>=18
    }
    private fun setDynamicallyWallpaper(icon:String):Int{
        return when(icon.dropLast(1)){
            "01"->{
                initWeatherView(PrecipType.CLEAR)
                R.drawable.snow_bg
            }
            "02","03","04"->{
                initWeatherView(PrecipType.CLEAR)
                R.drawable.cloudy_bg
            }
            "09","10","11"->{
                initWeatherView(PrecipType.RAIN)
                R.drawable.rainy_bg
            }
            "13"->{
                initWeatherView(PrecipType.SNOW)
                R.drawable.snow_bg
            }
            "50"->{
                initWeatherView(PrecipType.CLEAR)
                R.drawable.haze_bg
            }
            else -> 0
        }
    }

    private fun setEffectRainSnow(icon:String){
         when(icon.dropLast(1)){
            "01"->{
                initWeatherView(PrecipType.CLEAR)

            }
            "02","03","04"->{
                initWeatherView(PrecipType.CLEAR)

            }
            "09","10","11"->{
                initWeatherView(PrecipType.RAIN)

            }
            "13"->{
                initWeatherView(PrecipType.SNOW)

            }
            "50"->{
                initWeatherView(PrecipType.CLEAR)

            }

        }
    }
    private fun initWeatherView(type:PrecipType){
        binding.weatherView.apply {
            setWeatherData(type)
            angle=-20
            emissionRate=100.0f
        }
    }
}

